use diesel::prelude::*;

use crate::todo::models;

/// Run query using Diesel to find todo by uid and return it.
pub fn find_user_by_uid(
    uid: i32,
    conn: &SqliteConnection,
) -> Result<Option<models::Todo>, diesel::result::Error> {
    use crate::todo::schema::todos::dsl::*;

    let todo = todos
        .filter(id.eq(uid))
        .first::<models::Todo>(conn)
        .optional()?;
    Ok(todo)
}

/// Run query using Diesel to insert a new database row and return the result.
pub fn insert_new_user(
    // prevent collision with `name` column imported inside the function
    nm: &str,
    conn: &SqliteConnection,
) -> Result<models::Todo, diesel::result::Error> {
    // It is common when using Diesel with Actix web to import schema-related
    // modules inside a function's scope (rather than the normal module's scope)
    // to prevent import collisions and namespace pollution.
    use crate::todo::schema::todos::dsl::*;

    let new_user = models::Todo {
        id:1,
        text: nm.to_owned(),
        completed:false,
    };

    diesel::insert_into(todos).values(&new_user).execute(conn)?;//.get_results(&conn)?;

    Ok(new_user)
}
